package com.jxs.android.ges;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.xmlpull.v1.XmlPullParserException;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.LinearLayout;

import com.jxs.android.soap.BuWebService;
import com.jxs.android.soap.IWebService;
import com.jxs.android.soap.SoapUtil;
import com.jxs.android.util.HandlerHolder;
import com.jxs.android.util.MemoryUtil;
import com.jxs.android.util.Timer;
import com.jxs.android.weiget.BuAlertDailog;
import com.jxs.android.weiget.BuLoadingDailog;
import com.jxs.android.weiget.TopBar;
import com.jxs.android.weiget.WheelDateDialog;
import com.jxs.android.weiget.WorkLogEditItem;
import com.jxs.android.weiget.WorkLogEditSubTitle;

@SuppressLint("HandlerLeak")
public class WorkLogNewCreate extends AbstractActivity implements WorkLogDetailManager.UI {

	private BuLoadingDailog progressDialog;
	private ViewHolder detailViewHolder;
	private String wl_id = "";
	private LinearLayout bu_common_extends_detail;
	private LinearLayout bu_common_extends_todayList;
	private LinearLayout bu_common_extends_tomorrowList;
	private WorkLogEditSubTitle todayListBar;
	private WorkLogEditSubTitle tomorrowListBar;
	private Context context;

	private WorkLogSaveHolder workLogSaveHolder;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		context = this;
		initTopBar(savedInstanceState, R.layout.bu_work_log_new_create);
		bu_common_extends_detail = (LinearLayout) findViewById(R.id.bu_common_extends_detail);
		bu_common_extends_todayList = (LinearLayout) findViewById(R.id.bu_common_extends_todayList);
		bu_common_extends_tomorrowList = (LinearLayout) findViewById(R.id.bu_common_extends_tomorrowList);
		InitViewHolder initViewHolder = new InitViewHolder(this);
		detailViewHolder = initViewHolder.init();
		bu_common_extends_detail.removeAllViews();
		bu_common_extends_detail.addView(initViewHolder.getView());
		initHolder();
		initSubBar();
		updateDetail();
		getYesterdayPlanList();
	}

	private void initHolder() {
		workLogSaveHolder = new WorkLogSaveHolder(handler, wl_id);
	}

	private void initSubBar() {
		todayListBar = (WorkLogEditSubTitle) findViewById(R.id.todayList_bar);
		tomorrowListBar = (WorkLogEditSubTitle) findViewById(R.id.tomorrowList_bar);

		todayListBar.setAddOptionListen(todayListBarListen);
		tomorrowListBar.setAddOptionListen(tomorrowListBarListen);
	}

	private WorkLogEditSubTitle.AddOptionListen todayListBarListen = new WorkLogEditSubTitle.AddOptionListen() {

		@Override
		public void logic(View v) {
			addTodayAndTomorrowListItem();
		}
	};

	private void addTodayAndTomorrowListItem() {
		WorkLogEditItem todayItm = new WorkLogEditItem(context, todayListWorkLogEditItems.size() + 1);
		todayItm.setValue("", "");
		todayListWorkLogEditItems.add(todayItm);
		bu_common_extends_todayList.addView(todayItm);

		WorkLogEditItem tomorrowItem = new WorkLogEditItem(context, tomorrowListWorkLogEditItems.size() + 1);
		tomorrowItem.setValue("", "");
		tomorrowListWorkLogEditItems.add(tomorrowItem);
		bu_common_extends_tomorrowList.addView(tomorrowItem);
	}

	private WorkLogEditSubTitle.AddOptionListen tomorrowListBarListen = new WorkLogEditSubTitle.AddOptionListen() {

		@Override
		public void logic(View v) {
			addTodayAndTomorrowListItem();
		}
	};

	@Override
	public void topBarLogic(TopBar topBar) {
		super.topBarReturn(topBar);
		topBar.setLogicBtnText("保存");
		topBar.setTitle("新建工作日志");
		topBar.showLogicBtn();
		topBar.hindFilter();
		topBar.hindSpinnerBtn();
		topBar.setLogicBtnListern(new TopBar.LogicBtnListern() {
			@Override
			public void onClickLogicBtn() {
				if (todayListWorkLogEditItems.size() == 0 && tomorrowListWorkLogEditItems.size() == 0) {
					errorMsgPop("未作计划无法保存");
					return;
				}
				progressDialog.show();
				update(todayListWorkLogEditItems, tomorrowListWorkLogEditItems);

			}
		});
	}

	/**
	 * 修改
	 * 
	 * @param todayListWorkLogEditItems
	 * @param tomorrowListWorkLogEditItems
	 */
	private void update(List<WorkLogEditItem> todayListWorkLogEditItems, List<WorkLogEditItem> tomorrowListWorkLogEditItems) {
		workLogSaveHolder.saveWorkLog(GesApplication.getUserInfo().getTicket(), detailViewHolder.create_date.getText().toString(), todayListWorkLogEditItems,
				tomorrowListWorkLogEditItems);
	}

	private void getYesterdayPlanList /* 【读取前一天的计划接口】 */() {
		progressDialog = new BuLoadingDailog(this);
		progressDialog.showLoading(R.string.load_and_wait);
		new Thread(new Runnable() {
			@Override
			public void run() {
				getYesterdayPlanList(GesApplication.getUserInfo().getTicket(), detailViewHolder.create_date.getText().toString());
			}
		}).start();
	}

	private void getYesterdayPlanList(String ticket, String date) {
		// 2.4.3 getWorkLogDetail 【获取工作日志详单接口】
		String wsdl_url = GesApplication.WSDL_URL;// wsdl
		String namespace = GesApplication.WSDL_NAME_SPACE;// namespace
		String methodName = "getYesterdayPlanList";// 要调用的方法名称
		SoapObject request = new SoapObject(namespace, methodName);
		request.addProperty("ticket", ticket);
		request.addProperty("date", date);
		BuWebService webService = new BuWebService(wsdl_url, request);
		webService.setDoNet(false);
		webService.requestWSDL(new IWebService() {
			@Override
			public void logic(SoapSerializationEnvelope envelope) throws IOException, XmlPullParserException {
				SoapObject response = (SoapObject) envelope.getResponse();
				paser(response);
			}

			@Override
			public void error(String message, Exception e) {
				Message msg = new Message();
				msg.what = ERROR_MSG;
				msg.obj = message;
				handler.sendMessage(msg);
			}

		});
	}

	private void paser(SoapObject soapObject) {
		if (null != soapObject) {
			String stauts = soapObject.getProperty("status").toString();
			SoapObject msgObjec = (SoapObject) soapObject.getProperty("msg");
			String message = msgObjec.getProperty("message").toString();
			if ("-2".equals(stauts)) {
				Message msg = new Message();
				msg.what = ERROR_MSG;
				msg.obj = message;
				handler.sendMessage(msg);
			} else if ("-1".equals(stauts)) {
				Message msg = new Message();
				msg.what = TO_LOGIN;
				msg.obj = message;
				handler.sendMessage(msg);
			} else if ("0".equals(stauts)) {
				Message msg = new Message();
				msg.what = UPDATE_LIST_UI;
				msg.obj = (SoapObject) soapObject.getProperty("retMsg");
				handler.sendMessage(msg);
			}
		}
	}

	private final int UPDATE_LIST_UI = 0x101;
	private final int ERROR_MSG = 0x1013;
	private final int TO_LOGIN = 0x1019;
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			if (!MemoryUtil.isCurrentActivity(WorkLogNewCreate.class)) {
				return;
			}

			if (null != progressDialog && progressDialog.isShowing()) {
				progressDialog.dismiss();
			}
			if (msg.what == UPDATE_LIST_UI) {
				initTodayList((SoapObject) msg.obj);
				initTomorrowList();
			} else if (msg.what == ERROR_MSG) {
				errorMsgPop(msg.obj.toString());
			} else if (msg.what == TO_LOGIN) {
				errorMsgToLogin(msg.obj.toString());
			} else if (msg.what == HandlerHolder.What.WORK_LOG_SAVE_RESLT_OK) {
				wl_id = msg.getData().getString("wl_id");
				show(wl_id, "创建成功！");
			}
		}
	};

	private void show(final String wl_id, final String message) {

		BuAlertDailog.builder(context, "提示", message, new BuAlertDailog.AlertOkAndCancelListener() {

			@Override
			public void okLogic(Dialog dialog) {
				Intent intent = new Intent(context, WorkLogGetSmsContent.class);
				Bundle bundle = new Bundle();
				bundle.putString("wl_id", wl_id);
				intent.putExtras(bundle);
				startActivity(intent);
				dialog.cancel();
				finish();
			}

			@Override
			public String getOkText(Context context) {
				return "发送短信";
			}

			@Override
			public String getCancleText(Context context) {
				return getString(R.string.prompt_cancel);
			}

			@Override
			public void cancelLogic(Dialog dialog) {
				dialog.cancel();
			}
		}).show();

	}

	private List<WorkLogEditItem> todayListWorkLogEditItems = new ArrayList<WorkLogEditItem>();

	private void initTodayList(SoapObject todayList) {
		todayListWorkLogEditItems.clear();
		bu_common_extends_todayList.removeAllViews();
		if (null != todayList) {
			for (int i = 0; i < todayList.getPropertyCount(); i++) {
				SoapObject taskBeanObject = (SoapObject) todayList.getProperty(i);
				String contentStr = SoapUtil.getValue(taskBeanObject, "content");
				String noteStr = SoapUtil.getValue(taskBeanObject, "note");
				WorkLogEditItem child = new WorkLogEditItem(this, i + 1);
				child.setValue(contentStr, noteStr);
				todayListWorkLogEditItems.add(child);
				bu_common_extends_todayList.addView(child);
			}
		}

		int todayListSize = todayListWorkLogEditItems.size();
		if (todayListSize < 3) {
			for (int index = todayListSize; index < 3; index++) {
				WorkLogEditItem child = new WorkLogEditItem(this, index + 1);
				child.setValue("", "");
				todayListWorkLogEditItems.add(child);
				bu_common_extends_todayList.addView(child);
			}
		}

	}

	private List<WorkLogEditItem> tomorrowListWorkLogEditItems = new ArrayList<WorkLogEditItem>();

	private void initTomorrowList() {
		int tomorrowListSize = tomorrowListWorkLogEditItems.size();
		if (tomorrowListSize < 3) {
			for (int index = tomorrowListSize; index < 3; index++) {
				WorkLogEditItem child = new WorkLogEditItem(this, index + 1);
				child.setValue("", "");
				tomorrowListWorkLogEditItems.add(child);
				bu_common_extends_tomorrowList.addView(child);
			}
		}
	}

	private void updateDetail() {
		detailViewHolder.staff_name.setText(GesApplication.getUserInfo().getName());// 工号
		detailViewHolder.industry_type_name.setText(GesApplication.getUserInfo().getIndustry_type_name());
		detailViewHolder.create_date.setText(Timer.getSDFyyyyMMdd().format(System.currentTimeMillis()));// 姓名
		detailViewHolder.update_date.setText("");// 分公司

		findViewById(R.id.create_date).setBackgroundResource(R.drawable.roundlist_single);
		findViewById(R.id.create_date).setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				showDateDialog();
			}
		});
	}

	private void showDateDialog() {
		WheelDateDialog dateDialog = new WheelDateDialog(this, 0x8787, detailViewHolder.create_date.getText().toString());
		dateDialog.setDateChangeListener(new WheelDateDialog.DateChangeListener() {

			@Override
			public void onKeySave(int requestCode, String dateTimeValue) {
				detailViewHolder.create_date.setText(dateTimeValue);
				getYesterdayPlanList();
			}
		});
		dateDialog.show();
	}
}
